const logger = require('../config/logger');

const loggerMiddleware = (req, res, next) => {
  const startTime = Date.now();
  
  // 请求日志
  logger.http(`${req.method} ${req.url} - 开始请求`);

  // 响应拦截
  const originalEnd = res.end;
  res.end = function(...args) {
    const responseTime = Date.now() - startTime;
    const statusCode = res.statusCode;
    
    // 根据状态码选择日志级别
    const logLevel = statusCode >= 400 ? 'error' : 'info';
    
    logger[logLevel](
      `${req.method} ${req.url} - ${statusCode} - ${responseTime}ms`
    );
    
    originalEnd.apply(res, args);
  };

  next();
};

module.exports = loggerMiddleware;